using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DocLibApp
{
	public partial class FormFileImport : FormBase
	{
		private string DocFileName = "";

		public FormFileImport()
		{
			InitializeComponent();
            SetupControls();
		}

        /// <summary>
        /// pre-populate file import form with some values
        /// </summary>
        /// <param name="ht"></param>
        public FormFileImport(System.Collections.Hashtable ht)
        {
            InitializeComponent();
            SetupControls();

            LoadDataFromHashToControls(groupBox_DocumentInformation.Controls, ht);
        }

		#region INITIALIZATION

		private void SetupControls()
		{
            util.SetupCombo(cboCategory, FormMain.DocLibStaticValueList, "DOC_CATEGORY");
            util.SetupCombo(cboDocType, FormMain.DocLibStaticValueList, "DOC_TYPE");
            util.SetupCombo(cboOwner, FormMain.DocLibStaticValueList, "DOC_OWNER");
            util.SetupCombo(cboImportance, FormMain.DocLibStaticValueList, "DOC_IMPORTANCE");
            util.SetupCombo(cboDocLocation, FormMain.DocLibStaticValueList, "DOC_LOCATION");

            DocumentDateTimePicker.Value = System.DateTime.Now;
		}

		private void FormFileImport_Load(object sender, EventArgs e)
		{
		}
		#endregion //EO INITIALIZATION

		#region Event Handlers
        private void AddFileToList(string filename)
        {
            if (!lsv_FileList.IsItemAlreadyInList(filename))
            {
                string FileNameOnly = System.IO.Path.GetFileName(filename);
                string PathOnly = System.IO.Path.GetDirectoryName(filename);

                ListViewItem newItem = new ListViewItem(FileNameOnly);
                newItem.SubItems.Add(PathOnly);
                newItem.Tag = filename;

                lsv_FileList.Items.Add(newItem);
            }
            else
            {
                ShowMessage("The file you are trying to add to the list already exist.");
            }
        }

		private string CheckInput()
		{
			string err = "";
            
            if (lsv_FileList.Items.Count == 0)
                err += "\nYou have to add file to the file list.";
			if (txtDocTitle.Text.Trim() == "")
				err += "\nA Document Title is required.";
			if (cboCategory.SelectedValue == null || cboCategory.SelectedValue.ToString() == "0")
				err += "\nYou have to select a document category.";
			if (cboOwner.SelectedValue == null || cboOwner.SelectedValue.ToString() == "0")
				err += "\nYou have to select a owner from the list.";
			return err;
		}
		
        private void SaveToDMS()
		{
            try
            {
                wait_start("Saving Document to Library ...");
                System.Collections.Hashtable ht = new System.Collections.Hashtable();

                string err = CheckInput();
                if (err != "")
                    MessageBox.Show(err);
                else
                {
                    btnSaveToDMS.Enabled = false;

                    ht = SaveDataToHashFromControls(groupBox_DocumentInformation.Controls);

                    //only saving the filename of the first item in the list to the field ORIGINAL_FILENAME
                    ht["ORIGINAL_FILENAME"] = System.IO.Path.GetFileName(lsv_FileList.Items[0].Tag.ToString());

                    string RandomFileName = util.GenerateRandomFileName();

                    ht["DOC_ID"] = RandomFileName;

                    string GeneratedFileName = System.IO.Path.Combine(FormMain.DocLib_DocumentPath, RandomFileName + ".zip");

                    List<string> filelist = new List<string>();
                    filelist = lsv_FileList.SaveItemsIntoStringList();

                    util.CompressFileListIntoZip(filelist, GeneratedFileName, "Document Library", def.ZipPassword, true);

                    System.IO.FileInfo fi = new System.IO.FileInfo(GeneratedFileName);
                    if (System.IO.File.Exists(GeneratedFileName) && (fi.Length > 0))
                    {
                        doc_operation.CreatNewDocument(ht);
                    }

                    ShowMessage("Save to Doc Library successfully!");

                    wait_end();

                    this.Close();
                }
            }
            catch (System.Exception ex)
            {
                HandleEx(ex);
            }
		}

        private void FillInDefault()
        {
            if (lsv_FileList.Items.Count > 0)
                txtDocTitle.Text = lsv_FileList.Items[0].Text.Trim();

            cboCategory.SelectedIndex = 1;
            cboOwner.SelectedIndex = 1;
            cboImportance.SelectedIndex = 1;
            cboDocType.SelectedIndex = 1;
            cboDocLocation.SelectedIndex = 1;
            txtNumPages.Text = "1";
        }

		private void btnOpenFile_Click(object sender, EventArgs e)
		{
			OpenFileDialog openFileDialog1 = new OpenFileDialog();

			openFileDialog1.InitialDirectory = "c:\\";
			openFileDialog1.Filter = "PDF files (*.pdf)|*.pdf|txt files (*.txt)|*.txt|All files (*.*)|*.*";
			openFileDialog1.FilterIndex = 3;
            openFileDialog1.Multiselect = true;
			openFileDialog1.RestoreDirectory = true;

			if (openFileDialog1.ShowDialog() == DialogResult.OK)
			{
				if (openFileDialog1.FileNames.Length > 0)
				{
                    foreach (string filename in openFileDialog1.FileNames)
                    {
                        AddFileToList(filename);
                    }
				}
			}

		}
		private void button1_Click(object sender, EventArgs e)
		{
			SaveToDMS();
		}

        private void FormFileImport_DragDrop(object sender, DragEventArgs e)
        {
            string[] asFiles = e.Data.GetData(DataFormats.FileDrop) as string[];

            if (asFiles != null)
            {
                foreach (string filename in asFiles)
                {
                    AddFileToList(filename);
                }
            }
        }

        private void FormFileImport_DragEnter(object sender, DragEventArgs e)
        {
            // If the data is a file or a bitmap, display the copy cursor.
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void label1_DoubleClick(object sender, EventArgs e)
        {
            if (this.DocFileName != "")
            {
                util.RunFile(this.DocFileName);
            }
        }

        private void btnDefault_Click(object sender, EventArgs e)
        {
            FillInDefault();
        }
		#endregion //EO Event Handlers

        private void lsv_FileList_DoubleClick(object sender, EventArgs e)
        {
            if (lsv_FileList.SelectedItems.Count > 0)
            {
                ListViewItem aitem = lsv_FileList.SelectedItems[0];
                if (aitem.Tag != null && !string.IsNullOrEmpty(aitem.Tag.ToString()))
                    util.RunFileWaitForExit(aitem.Tag.ToString());
            }
        }

        private void btnPickTemplate_Click(object sender, EventArgs e)
        {
            string template_id = PickTemplate();

            if (!string.IsNullOrEmpty(template_id))
            {
                wait_start();

                System.Collections.Hashtable ht = doc_template.Get_Template_Fields(template_id); //get template fields
                if (ht.Count > 0)
                {
                    LoadDataFromHashToControls(groupBox_DocumentInformation.Controls, ht);
                }

                wait_end();
            }
        }


	}
}